package com.zwt.interceptor;

import com.zwt.annotation.NoAuthAnnotation;
import com.zwt.model.UserInfo;
import com.zwt.redis.Redis;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zwt on 2018/9/6.
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private Redis redis;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器来了");
        HandlerMethod hm = null;
        if (handler instanceof HandlerMethod) {
            hm = (HandlerMethod) handler;
        } else {
            return true;
        }
        if (isNotAuth(hm)) {
            return true;
        }
        return checkToken(request,response);
    }



    private boolean isNotAuth(HandlerMethod method){
        /**
         * 获取注解 如果有该注解 说明该请求不需要被拦截 放行
         */
        Class<?> beanType = method.getBeanType();
        if(null!=beanType){
            NoAuthAnnotation annotation = beanType.getAnnotation(NoAuthAnnotation.class);
            if(null!=annotation){
                return true;
            }
        }
        return false;
    }


    private boolean checkToken(HttpServletRequest request,HttpServletResponse response) throws IOException{
        String token = request.getParameter("token");
        if(StringUtils.isBlank(token)){
            redirectFail(response);
            return false;
        }
        UserInfo userInfo = redis.get(token, UserInfo.class);
        if(null==userInfo || null==userInfo.gettAccountUser() || null==userInfo.gettAccountUser().getAccountUserId()){
            redirectFail(response);
            return false;
        }
        return true;
    }


    private static final String FAIL_URL = "/app/login/fail";

    private static void redirectFail(HttpServletResponse response) throws IOException {
        response.sendRedirect(FAIL_URL);
    }
}
